import random
import time
from django.views import View
from django.http import JsonResponse
from api.views.login import clean_form
from django import forms
from django.core.mail import send_mail
from blogproject import settings
from django.core.handlers.wsgi import WSGIRequest
from threading import Thread
from app01.models import UserInfo
from api.models import Email

class EmailForm(forms.Form):
    email = forms.EmailField(error_messages={'required': '请输入邮箱', "invalid": '请输入正确邮箱'})

    def clean_email(self):
        email = self.cleaned_data['email']
        user = UserInfo.objects.filter(email=email)
        if user:
            self.add_error('email','邮箱不允许重复')
        return email
class Api_send_email(View):
    def post(self, request: WSGIRequest):
        res = {
            'code': 333,
            'msg': '验证码获取成功',
            'self': None
        }
        # email = request.data.get('email')
        form = EmailForm(request.data)
        if not form.is_valid():
            res['self'], res['msg'] = clean_form(form)
            return JsonResponse(res)

        # 发送邮件 设置超时时间
        # 从session里边读取
        valid_email_obj = request.session.get('valid_email_obj')
        if valid_email_obj:
            time_stamp = valid_email_obj['time_stamp']
            now_stamp = time.time()
            if (now_stamp - time_stamp) < 10:
                res['msg'] = '请求过于频繁'
                return JsonResponse(res)

        valid_email_code = ''.join(random.sample('1234567890', 6))
        request.session['valid_email_obj'] = {
            'code': valid_email_code,
            'email': form.cleaned_data['email'],
            'time_stamp': time.time()
        }
        msg_from = settings.EMAIL_HOST_USER  # 发送人地址
        to = [form.cleaned_data.get('email')]  # 收件人地址
        subject = 'dkzcm的个人博客,完善信息'  # 电子邮件主题
        content = f'您的邮箱验证码为{valid_email_code},有效期大概为3分钟'  # 发送内容
        Thread(target=send_mail, args=(
            subject,
            content,
            msg_from,
            to,
            False
        )).start()

        Email.objects.create(
            email=form.cleaned_data.get('email'),
            content='完善信息',
        )
        res['code'] = 0
        return JsonResponse(res)
